package com.education.seckill.controller;

import com.education.seckill.entity.SeckillGood;
import com.education.seckill.mq.mqSender;
import com.education.seckill.service.ISeckillGoodService;
import com.education.seckill.service.ISeckillOrderService;
import com.education.seckill.utils.R;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Mr.Tang
 * @since 2022-06-20
 */
@CrossOrigin
@Transactional
@RestController
@RequestMapping("/seckillOrder")
public class SeckillOrderController implements InitializingBean {

    @Autowired
    private ISeckillOrderService seckillOrderService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private mqSender mqSender;

    @Autowired
    private ISeckillGoodService seckillGoodService;

    Map<String,Boolean> haveStock = new HashMap<String,Boolean>();

    /**
     *
     * -1 : 库存不足
     * 0：排队中
     *1：秒杀成功
     *
     * */
    @Transactional
    @GetMapping("createOrder/{id}")
    public R createOrder(@PathVariable("id")Long id){

        if(!haveStock.get("secgoodCount" + id)){
            return R.ok().data("stock",-1);
        }

        //预减库存
        Long stock = redisTemplate.opsForValue().decrement("secgoodCount" + id);
        System.out.println(stock);
        if (stock < 1){
                haveStock.put("secgoodCount" + id,false);
                return R.ok().data("stock",-1);
        }

        //下单
        mqSender.sendSeckillMes(id);

        return R.ok().data("stock",1);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        List<SeckillGood> list = seckillGoodService.list();
        for (SeckillGood s:list) {
            haveStock.put("secgoodCount" + s.getSGoodId(),true);
        }

    }
}
